#include "cgzITask.h"
#include "cgzCThreadPool.h"

cgzIData::~cgzIData()
{
}

static std::atomic<int> s_lastObjectId = 0;
cgzITask::cgzITask(cgzCThreadPool *pool, const char *name, cgzETask tenum)
    : m_id(-1),
      m_name(name),
      m_tenum(tenum),
      m_busy(false),
      m_bShutdown(false),
      m_bRunning(true),
      m_pool(pool),
      m_thread(nullptr)
{
    m_id = ++s_lastObjectId;
}

int cgzITask::getId() const
{
    return m_id;
}

const char *cgzITask::getName() const
{
    return m_name.c_str();
}

cgzETask cgzITask::getTEnum() const
{
    return m_tenum;
}

bool cgzITask::retTask(cgzIData *cgzTask)
{
    m_retTask.push_back(cgzTask);
    return true;
}

bool cgzITask::addTask(cgzIData *cgzTask)
{
    m_runTask.push_back(cgzTask);
    return true;
}

bool cgzITask::regTask(const char *target, cgzIData *pTask)
{
    m_pool->addTask(m_name.c_str(), target, pTask);
    return true;
}

bool cgzITask::setFree()
{
    m_busy = false;
    return true;
}
bool cgzITask::setBusy()
{
    m_busy = true;
    return true;
}

bool cgzITask::basBusy()
{
    return m_busy;
}

bool cgzITask::casBusy()
{
    return false;
}

void cgzITask::service()
{
    setBusy();
    m_pool->addTask(m_name.c_str(), this);
    setFree();
}

bool cgzITask::shutdown()
{
    m_bShutdown = true;
    return m_bShutdown;
}

bool cgzITask::mabystop()
{
    std::shared_lock lock(m_rwmutex);
    if (m_busy)
    {
        return false;
    }

    if (m_runTask.size() > 0)
    {
        return false;
    }

    if (m_retTask.size() > 0)
    {
        return false;
    }

    if (m_synTask.size() > 0)
    {
        return false;
    }

    return true;
}

bool cgzITask::realstop()
{
    m_bRunning = false;
    return true;
}

cgzCThreadPool *cgzITask::getPool()
{
    return m_pool;
}
